

var sourceType = [
  ['camera'],
  ['album'],
  ['camera', 'album']
]
var sizeType = [
  ['compressed'],
  ['original'],
  ['compressed', 'original']
]
var app = getApp();
var util = require('../../utils/util.js');
const applet_park_api_url = app.globalData.applet_park_api_url;
const applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl:applet_park_api_url_imgUrl,
    imageList: [],
    imagepreList: [],
    sources:'',
    pics: [],
    customerServiceshow: false,
    directo: false,
    sysemid:'',
    detail: {},
    evaluations: {},
    evaluationsshow: false,
    calcontent: '',
    calcontent2: '',
    currenttab: '',
    showModal: false,
    showModal2: false,
    starClassNum: [],
    items: [],
    imglist: [],
    list: [{
        // 状态
        id: 0,
        // title
        name: "一楼热水泵房",
        // 时间

      }, {
        id: 1,
        name: "工程-车库-B1F-热水泵房",

      }, {
        id: 2,
        name: "工程-学术报告厅-1F-报告厅低压配电室",

      }

      , {
        id: 3,
        name: "一楼热水泵房",

      }


    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.workid) {
      this.setData({
        workid: options.workid
      })
    }
    var userRoles = wx.getStorageSync("userRoles");
    //客服
    if (userRoles.indexOf('customerService') != -1) {
      this.setData({
        customerServiceshow: true
      })
    }
    //主管
    if ((userRoles.indexOf('engineeringSupervisor') != -1) || (userRoles.indexOf('safetySupervisor') != -1) || (userRoles.indexOf('environmentalSupervisor') != -1)) {
      this.setData({
        directo: true
      })
     
    }
    var id = wx.getStorageSync("id");
    this.setData({
      sysemid: id
    })
  },
  go: function () {
    this.setData({
      showModal: false
    })
  },
  go2: function () {
    this.setData({
      showModal2: false
    })
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(this.data);
  },
  //退回
  calsubmit() {
    var that = this
    let url = '';

    if (!that.data.calcontent) {
      util.showModal('请填写退回备注');
      return
    }
    var id = wx.getStorageSync("id");

    if (that.data.model == 'm1') {
      url = applet_park_api_url + '/api/repairs/return'

    }

    if (that.data.model == 'm2') {
      url = applet_park_api_url + '/api/repairs/cancel'

    }

    wx.request({
      url: url,
      data: {
        repairId: that.data.workid,
        assignorId: id,
        reason: that.data.calcontent
      },
      method: 'POST',
      header: {
        'content-type': 'application/json;charset=UTF-8',
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '操作成功',
          })
          that.go();
          that.detail();
          that.loadData();
          that.evaluations()

        } else {

          wx.showToast({
            title: '操作失败',
          })
        }
      },
      fail: function (e) {
        // util.showToast("网络异常")
        wx.showToast({
          title: '网络异常',
        })
      }
    })
  },

  submitcomplete2(e) {
    var that = this;
    var workid = e.currentTarget.dataset.workid;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs',
      method: "PUT",
      data: {
        id: workid,
        assignorId: id,
        consignorId: id,
        status: 5
      },
      success(res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '操作成功',
          })

          that.detail();
          that.loadData();
          that.evaluations()
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  submitcomplete(e) {

    var that = this;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs',
      method: "PUT",
      data: {
        id: that.data.workid,
        assignorId: id,
        consignorId: id,
        status: 5,
        images: that.data.sources,
        reason: that.data.calcontent2
      },
      success(res) {
        if (res.data.code == 0) {
          that.go2();
          that.detail();
          that.loadData();
          that.evaluations()
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
//
  openzp: function (e) {
    var workid = e.currentTarget.dataset.workid;
    var model = e.currentTarget.dataset.model;
    this.setData({
      showModal: true,
      workid: workid,
      model: model,
      calcontent: '',
    })
  },
  complete: function (e) {
    var workid = e.currentTarget.dataset.workid;
    var model = e.currentTarget.dataset.model;
    this.setData({
      showModal2: true,
      workid: workid,
      model: model
    })
  },
  //指派
  customerAppoint(e) {
    var workid = e.currentTarget.dataset.workid;
    wx, wx.navigateTo({
      url: '../assignment/assignment?workid=' + workid,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  //节点
  loadData() {
    var that = this;
    wx.request({
      url: applet_park_api_url + '/api/repairTracks?repairId=' + that.data.workid,
      method: "GET",
      success(res) {
        console.res
        if (res.data.code == 0) {
          that.data.items = res.data.data;
          that.setData(that.data);
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  detail() {
    var that = this;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs/' + that.data.workid,
      method: "GET",
      success(res) {
        if (res.data.code == 0) {
          that.data.detail = res.data.data;
          // that.data.imglist = that.data.detail.image.split(",").slice(0, -1);
          let imglist = that.data.detail.image.split(",").slice(0, -1);
          let imglists = [];
          let url = that.data.imgUrl+"/";
          console.log(url)
          for (let item of imglist) {
            let list = url + item
            imglists.push(list);
          }
          that.data.imglist = imglists;
          // that.data.detail.createdTime = util.ymdFormat(that.data.detail.createdTime)
          that.setData(that.data);

        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },

  //评价
  evaluations() {
    var that = this;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repair/evaluations?repairId=' + that.data.workid,
      method: "GET",
      success(res) {
        if (res.data.code == 0) {
          var starClassNum = [];
          if (res.data.data != null) {
            starClassNum.length = res.data.data.starClassNum;
            that.data.evaluations = res.data.data;
            that.data.evaluationsshow = true;
            that.data.starClassNum.length = starClassNum.length;
            that.data.evaluations.createdTime = util.ymdFormat(that.data.evaluations.createdTime);
            that.data.imageList = res.data.data.image.split(",")
            that.setData(that.data);
          }

        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },

  previewImage(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var imgList = event.currentTarget.dataset.list; //获取data-list
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表

    })
  },
  previewImg: function(e) {
    var index = e.currentTarget.dataset.index;
    var imgArr = this.data.imglist;
    wx.previewImage({
      current: imgArr[index], //当前图片地址
      urls: imgArr, //所有要预览的图片的地址集合 数组形式
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  arrive(e) {
    var workid = e.currentTarget.dataset.workid;
    var that = this;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs',
      method: "PUT",
      data: {
        id: workid,
        assignorId: id,
        consignorId: id,
        status: 4
      },
      success(res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '操作成功',
          })
          that.detail();
          that.loadData();
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  chooseImage_album: function (e) {

    var that = this;
    wx.chooseImage({
      sourceType: sourceType[2],
      count: 3,
      success: function (res) {
        var imgsrc = res.tempFiles;
        var pics = that.data.pics.concat(imgsrc);
        var imageList = that.data.imageList.concat(imgsrc);
        // for (var obj of res.tempFiles) {
        //   obj.showOrder = that.data.showOrder;
        //   that.data.showOrder++;
        // }
        that.setData({
          pics: pics,
          imageList: imageList
        })
      }
    })
  },
  delect(e) {

    var pics = this.data.pics;
    var imageList = this.data.imageList;
    var imagepreList = this.data.imagepreList;
    var index = e.currentTarget.dataset.idx;
    pics.splice(index, 1);
    imageList.splice(index, 1);
    imagepreList.splice(index, 1);
    this.setData({
      pics: pics,
      imageList: imageList,
      imagepreList: imagepreList
    });
  },
  calsubmit2: function () {
    var that = this;
    var sources = '';
    wx.showLoading({
      title: '图片上传中',
      mask: true
    });
    var finished = true;
    // that.data.imageList = that.data.imageSingleList.concat(that.data.imageMultiList);
    for (var pic of that.data.imageList) {
      if (!pic.picUrl) { //false
        finished = false;
        break;
      }
    }

    if (finished) {
      wx.hideLoading();

      // wx.navigateBack();
      that.submitcomplete();
      return;
    }

    //用自执行函数,来解决循环内部的异步回调问题
    (function uploadImage(i) {
      if (i >= that.data.imageList.length) {
        return;
      }

      // var image = that.data.imageList[i];
      if (!that.data.imageList[i].picUrl && that.data.imageList[i].path) {
        var path = that.data.imageList[i].path;

        wx.uploadFile({
          url: applet_park_api_url + '/api/upload',
          filePath: path,
          name: 'files',
          success(res) {
            let response = JSON.parse(res.data);
            that.data.imageList[i].picUrl = "http://zjurainforest.com:9999" + response.data[0];

            sources = sources + response.data[0] + ",";
            // sources.push("https://njdhy.com.cn:7777" + response.data[0])
            that.data.sources = sources;
            that.setData(that.data);
            //检测下其他图片有没有传完
            var allFinished = true;
            for (var pic of that.data.imageList) {
              if (!pic.picUrl) { //false
                allFinished = false;
                break;
              }
            }
            if (allFinished) { //全部传完了,则隐藏加载按钮并返回
              wx.hideLoading();
              //数据回传录车页面,返回
              that.submitcomplete();
              //wx.navigateBack();
            } else {
              uploadImage(i + 1);
            }
          },
          fail(res) {
            
          }
        })
      } else {
        uploadImage(i + 1);
      }
    })(0);
  },
  gocomment(e) {
    wx.navigateTo({
      url: '../maintenanceRate/maintenanceRate?workid=' + e.currentTarget.dataset.workid,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.detail();
    this.loadData();
    this.evaluations()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    this.detail();
    this.loadData();
    this.evaluations()
    wx.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})